package com.nd.android.musicboxlibrary.service.player;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.URLUtil;

import com.common.StarAppConfig;
import com.nd.android.musicboxlibrary.GlobalSetting;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.FileInfo;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.ApiManager;
import com.nd.android.musicboxlibrary.business.comm.MagicNumber;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.business.comm.ThreadUtil;
import com.nd.android.musicboxlibrary.interf.IPlayerManager;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.service.notification.MusicNotification;
import com.nd.android.musicboxlibrary.ui.common.ImageLoaderUtil;
import com.nd.android.musicboxlibrary.ui.vip.decode.MusicDecoder;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.MusicBoxUtils;
import com.nd.android.musicboxlibrary.util.NdThread;
import com.nd.android.musicboxlibrary.util.Network;
import com.nd.android.musicboxlibrary.util.ToastUtil;
import com.ngds.library.downloadcenter.Downloads;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.product.android.utils.LogUtils;

/**
 * 音乐播放服务
 * Created 2014年9月15日 下午11:13:39
 * @version
 * @author zxq
 * @see
 */
@SuppressLint({ "DefaultLocale", "NewApi" })
public class MusicService extends Service implements OnCompletionListener,
OnBufferingUpdateListener, OnErrorListener, MagicNumber {

	/**
	 *
	 * <br>Created 2014年11月28日 上午12:05:46
	 * @author       wat.ztag
	 */
	@Override
	public void initMagicNumber() {
	}

	// 动作
	public static final String PLAYER_ACTION = "PLAYER_ACTION";
	// 歌曲ID
	public static final String MUSIC_ID = "MUSIC_ID";
	// 当前歌曲
	public static final String MUSIC_INFO = "MUSIC_INFO";
	// 歌曲时长
	public static final String MUSIC_DURATION = "MUSIC_DURATION";
	// 歌曲缓冲进度
	public static final String MUSIC_BUFFERED = "MUSIC_BUFFERED";
	// 跳转指针
	public static final String MUSIC_SEEKTO = "MUSIC_SEEKTO";
	// 播放进度
	public static final String MUSIC_POSITION = "MUSIC_POSITION";
	// 播放列表
	public static final String MUSIC_LIST = "MUSIC_LIST";
	// 是否正在播放
	public static final String MUSIC_ISPLAYING = "MUSIC_ISPLAYING";
	// 循环类型
	public static final String LOOP_TYPE = "LOOP_TYPE";
	// 顺序播放
	public static final int LOOP_TYPE_ORDER = 0;
	// 单曲循环
	public static final int LOOP_TYPE_LOOPING = 1;
	// 随机播放
	public static final int LOOP_TYPE_RADOM = 2;
	// 播放
	public static final int ACTION_PLAY = 1;
	// 暂停
	public static final int ACTION_PAUSE = 2;
	// 上一首
	public static final int ACTION_PREV = 3;
	// 下一首
	public static final int ACTION_NEXT = 4;
	// 停止
	public static final int ACTION_STOP = 5;
	// 跳转
	public static final int ACTION_SEEK_TO = 6;
	// 更新播放列表
	public static final int ACTION_LIST = 7;
	// 更新循环类型
	public static final int ACTION_LOOP_TYPE = 8;
	// 循环类型
	private int mLoopType = 0;
	/**歌曲列表*/
	private List<MusicInfo> mLstMusic = new ArrayList<MusicInfo>();
	// 媒体播放器
	private MediaPlayer mPlayer;
	private Handler mHandler = new MusicHandler();
	// 是否暂停
	private boolean mIsPause;
	// 跳转标记
	private int mSeekTo;
	// 歌曲序号
	private int mMusicIndex;
	private int mDuration;
	private BroadcastReceiver mNetStateReceiver = new NetStateReceiver();
	private NotificationManager mNm;
	private boolean mIsNetMusic;
	private MusicInfo mCurrentMusic;
	private NdThread mPrepareTask;
	private boolean mIsPreparing;
	// 是否允许使用数据网络播放网络音乐
	private boolean mMayPlayNetMusic = false;
	private int mBufferPercent = -1;
	private Map<String, Bitmap> mMapIcon = new HashMap<String, Bitmap>();
	private AudioManager mAam;
	private Dialog mConfirmPlayNetMusicDialog;
	private OnAudioFocusChangeListener mOfcl = new OnAudioFocusChangeListener() {
		private boolean isPlaying;
		@Override
		public void onAudioFocusChange(int focusChange) {
			switch (focusChange) {
			case AudioManager.AUDIOFOCUS_LOSS:
				// BUG 61565 要求恢复后接着播放，正常情况失去焦点因为不知道什么时候才能恢复，是要释放音乐相关资源的。
				//                mAam.abandonAudioFocus(this);
				//                stop(true);
				//                releaseMediaPlayer();
				//                break;

			case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
			case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
				isPlaying = false;
				if (mPlayer != null) {
					isPlaying = mPlayer.isPlaying();
					if (isPlaying) {
						pause();
					}
				}
				break;

			case AudioManager.AUDIOFOCUS_GAIN:
				if (isPlaying) {
					play();
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		init();
	}

	/**
	 * 初始化
	 * Created 2014-7-8 下午10:34:25
	 * @author zxq
	 */
	private void init() {
		mAam = (AudioManager) getSystemService(AUDIO_SERVICE);
		sendPlayerState(ACTION_STOP);
		initPlayer();
		LogUtils.v("MusicService.java -- jiangwb", "init() -- NdThread -- 更新播放列表 -- start");
		mLstMusic.addAll(ManagerFactory.getPlaylistInstance(getApplicationContext())
				.getMusicListOfPlaying());
		LogUtils.v("MusicService.java -- jiangwb", "init() -- NdThread -- 更新播放列表 -- end");
		new NdThread() {
			@Override
			protected Object doInBackground() {
				long id = ConfigHelper.getInstance(getApplicationContext()).loadLongKey(MUSIC_ID,
						-1);
				mCurrentMusic = findMusic(id);
				if (mCurrentMusic == null) {
					mCurrentMusic = ManagerFactory.getPlaylistInstance(getApplicationContext())
							.findMusic(id);
				}
				return null;
			}

			@Override
			protected void doSuccess(Object result) {
				ManagerFactory.getPlayerInstance().setCurrentMusic(mCurrentMusic);
				if (mCurrentMusic != null && !mLstMusic.isEmpty()) {
					mMusicIndex = mLstMusic.indexOf(mCurrentMusic);
					mSeekTo = ConfigHelper.getInstance(getApplicationContext()).loadIntKey(
							MUSIC_SEEKTO, 0);
				}
				Log.i("zxq", "init() mSeekTo = " + mSeekTo);
			}

			@Override
			protected void doFail(NdException result) {
			}
		}.execute();
		mLoopType = ConfigHelper.getInstance(getApplicationContext()).loadIntKey(LOOP_TYPE, 0);
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
		intentFilter.addAction("android.intent.action.PHONE_STATE");
		registerReceiver(mNetStateReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));
	}

	/**
	 * 初始化播放器
	 * Created 2014年9月15日 下午11:13:43
	 * @author zxq
	 */
	private void initPlayer() {
		mPlayer = new MediaPlayer();
		mPlayer.setOnErrorListener(this);
		mPlayer.setOnBufferingUpdateListener(this);
		mPlayer.setOnCompletionListener(this);
		mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		savePosition(0);
		ManagerFactory.getPlayerInstance().setPlayerState(IPlayerManager.PLAYER_STATE_STOPPED);
	}

	/**
	 * 查找歌曲
	 * Created 2014年9月15日 下午11:14:34
	 * @param id 歌曲ID
	 * @return MusicInfo 歌曲
	 * @author zxq
	 */
	private MusicInfo findMusic(long id) {
		for (MusicInfo music : mLstMusic) {
			if (music.getId() == id) {
				return music;
			}
		}
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("scj","------------Downloads.Impl.AUTHORITIES -----------"+ Downloads.Impl.AUTHORITIES );
		if (intent == null) {
			return super.onStartCommand(intent, flags, startId);
		}
		int playerAction = intent.getIntExtra(PLAYER_ACTION, 0);
		if (mPlayer == null && playerAction != ACTION_STOP) {
			initPlayer();
		}
		switch (playerAction) {
		// 停止
		case ACTION_STOP:
			stop(false);
			break;
			// 播放
		case ACTION_PLAY:
			if (intent.hasExtra(MUSIC_INFO)) {
				Serializable obj = intent.getSerializableExtra(MUSIC_INFO);
				if (obj instanceof MusicInfo) {
					MusicInfo musicInfo = (MusicInfo) obj;
					if (!mLstMusic.contains(musicInfo)) {
						if (mLstMusic.size() >= GlobalSetting.MUSIC_LIST_MAX) {
							mLstMusic.remove(0);
						}
						mLstMusic.add(musicInfo);
					} else if (musicInfo.equals(mCurrentMusic)
							&& (mPlayer.isPlaying() || mIsPreparing)) {
						// 当前正在播放此歌曲
						break;
					}
					stop(false);
					mMusicIndex = mLstMusic.indexOf(musicInfo);
					mSeekTo = 0;
				}
			} else if (mPlayer.isPlaying()) {
				break;
			}
			play();
			break;
			// 暂停
		case ACTION_PAUSE:
			pause();
			break;
			// 上一首
		case ACTION_PREV:
			prev();
			break;
			// 下一首
		case ACTION_NEXT:
			next();
			break;
			// 跳转
		case ACTION_SEEK_TO:
			seekTo(intent.getIntExtra(MUSIC_SEEKTO, 0));
			break;
			// 更新播放列表
		case ACTION_LIST:
			if (intent.hasExtra(MUSIC_LIST)) {
				LogUtils.v("MusicService.java -- jiangwb", "onStartCommand() -- ACTION_LIST -- 更新播放列表  -- start");
				Serializable obj = intent.getSerializableExtra(MUSIC_LIST);
				if (obj instanceof ArrayList<?>) {
					@SuppressWarnings("unchecked")
					ArrayList<MusicInfo> list = (ArrayList<MusicInfo>) obj;
					mLstMusic.clear();
					mLstMusic.addAll(list);
					updateCurrentMusicIndex();
					break;
				}
				LogUtils.v("MusicService.java -- jiangwb", "onStartCommand() -- ACTION_LIST -- 更新播放列表  -- end");
			}
			updateList();
			break;
			// 更新循环类型
		case ACTION_LOOP_TYPE:
			mLoopType = intent.getIntExtra(LOOP_TYPE, 0);
			break;
		default:
			break;
		}
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 快进
	 * Created 2014-7-8 下午10:16:36
	 * @param position 进度
	 * @author zxq
	 */
	private void seekTo(int position) {
		savePosition(position);
		if (!mIsPause) {
			pause();
			savePosition(position);
			play();
		}
	}

	/**
	 * 更新播放列表
	 * Created 2014-7-10 上午12:50:15
	 * @author zxq
	 */
	private void updateList() {
		mLstMusic.clear();
		new NdThread() {
			@Override
			protected Object doInBackground() {
				LogUtils.v("MusicService.java -- jiangwb", "updateList() -- NdThread -- 更新播放列表");
				mLstMusic.addAll(ManagerFactory.getPlaylistInstance(getApplicationContext())
						.getMusicListOfPlaying());
				return null;
			}

			@Override
			protected void doSuccess(Object result) {
				updateCurrentMusicIndex();
				if (mLstMusic != null && !mLstMusic.isEmpty() && mMusicIndex >= 0
						&& mMusicIndex < mLstMusic.size()) {
					// 更新对应的音乐信息
					ManagerFactory.getPlayerInstance().setCurrentMusic(mLstMusic.get(mMusicIndex));
				}
			}


			@Override
			protected void doFail(NdException result) {
			}
		}.execute();
	}

	/***********************************************************************************/
	/**
	 * 更新当前播放音乐和序号
	 * Created 2014-11-27 下午7:44:02
	 * @author       zxq
	 */
	private void updateCurrentMusicAndIndex() {
		if (mCurrentMusic != null && !mLstMusic.isEmpty()
				&& mLstMusic.contains(mCurrentMusic)) {
			mMusicIndex = mLstMusic.indexOf(mCurrentMusic);
		} else {
			mMusicIndex = 0;
		}
		if(mLstMusic != null && !mLstMusic.isEmpty()){
			//by jiangwb ， 加判断。
			//不加，会出现java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
			//2014-11-30 10:37:43 xiaomi 2s
			// 更新对应的音乐信息
			mCurrentMusic = mLstMusic.get(mMusicIndex);
			ManagerFactory.getPlayerInstance().setCurrentMusic(mCurrentMusic);
		}else{
			//by jiangwb ， 加判断。
			LogUtils.e("MusicService - jiangwb", "updateCurrentMusicAndIndex() -- mLstMusic 没有数据了。。。。");
		}
	}

	/**
	 * 更新当前播放音乐的序号
	 * Created 2014-11-27 下午7:44:02
	 * @author       zxq
	 */
	private void updateCurrentMusicIndex() {
		if (mCurrentMusic != null && !mLstMusic.isEmpty()
				&& mLstMusic.contains(mCurrentMusic)) {
			mMusicIndex = mLstMusic.indexOf(mCurrentMusic);
		} else {
			mMusicIndex = 0;
		}
	}

	/**
	 * 播放
	 * Created 2014-7-8 下午10:58:25
	 * @author zxq
	 */
	private void play() {
		if ( StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)) {
			playWhenVersion18();
		} else {
			playBelowVersion18();
		}
	}

	private void playWhenVersion18() {
		boolean prepared = preparePlay();
		if ( !prepared ) return;

		// 不是从暂停状态进入播放状态
		if (!mIsPause) {
			playFromNew();
		} else {
			playFromPause();
		}
	}

	private boolean preparePlay() {
		Log.i("zxq", "play()");
		mAam.requestAudioFocus(mOfcl, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

		if (mLstMusic == null || mLstMusic.isEmpty()) {
			ToastUtil.showShort(getApplicationContext(),
					R.string.mbx_play_list_is_empty);
			return false;
		} else if (mMusicIndex >= mLstMusic.size()) {
			mMusicIndex = 0;
		}
		if (mPlayer == null) {
			initPlayer();
		}
		return true;
	}

	private void playFromNew() {
		mMapIcon.clear();
		//越界保护——By HuangYK
		if (mLstMusic == null || mLstMusic.size() == 0) {
			return;
		}
		if (mMusicIndex < 0 || mMusicIndex > mLstMusic.size()) {
			mMusicIndex = 0;
		}
		mCurrentMusic = mLstMusic.get(mMusicIndex);
		commitMusicId();
		ManagerFactory.getPlayerInstance().setCurrentMusic(mCurrentMusic);
		mPlayer.reset();

		final String musicName = mCurrentMusic.getMusicName();
		String path = mCurrentMusic.getMusicPath();// 获取音乐在sd卡的路径地址
		String hq_path = mCurrentMusic.getHQMusicPath();// 获取高清音乐在sd卡的路径地址,by
		// jiagnwb
		// 已下载
		if (new File(hq_path).isFile()) { // 已下载
			Log.i("MusicService.java -- jiangwb", "mHQMusicIndex="
					+ mMusicIndex + ",hq_path=" + hq_path);
			path = hq_path;// by jiangwb ,如果sd卡有高清音质，默认先播放高清音质的
			mCurrentMusic.setHQ(true);
			mIsNetMusic = false;
			mBufferPercent = -1;

			final String originalMusicPath = path;
			ThreadUtil.executeMore(new Runnable() {
				@Override
				public void run() {
					// 解密文件
					Context context = getApplicationContext();
					FileInfo.cleanEncryptedMusicPath(context);
					final String encryptedMusicPath = MusicDecoder
							.getEncryptedMusicPath(context, musicName);
					MusicDecoder.xxteaDecrypt(originalMusicPath,
							encryptedMusicPath);

					mHandler.post( new Runnable() {
						@Override
						public void run() {
							postPlayFromNew(encryptedMusicPath);
						}
					});
				}
			});

		} else if ( new File(path).isFile()) { // 已下载
			Log.i("zxq", "mMusicIndex=" + mMusicIndex + ",path=" + path);
			mIsNetMusic = false;
			mBufferPercent = -1;

			postPlayFromNew(path);

		} else {
			path = mCurrentMusic.getMusicUrl();
			if (TextUtils.isEmpty(path) || !URLUtil.isValidUrl(path)) {
				ToastUtil.showShort(getApplicationContext(),
						R.string.mbx_music_file_error);
				sendPlayerState(ACTION_PAUSE);
				return;
			}
			Log.i("zxq", "mMusicIndex=" + mMusicIndex + ",url=" + path);
			mSeekTo = 0;
			mIsNetMusic = true;
			mBufferPercent = 0;

			postPlayFromNew(path);
		}
	}

	private void postPlayFromNew(String path) {
		Intent intent = MusicBoxUtils.getMusicServiceActionIntent();
		intent.putExtra(MUSIC_INFO, mCurrentMusic);
		sendBroadcast(intent);
		ConfigHelper.getInstance(getApplicationContext()).saveLongKey(MUSIC_ID,
				mCurrentMusic.getId());
		if (mIsNetMusic) {
			if (!Network.isNetworkAvaliable(getApplicationContext())) {
				ToastUtil.showShort(getApplicationContext(),
						R.string.mbx_no_net_for_play_net_music);
				sendPlayerState(ACTION_STOP);
				showNotification(false);
				return;
			} else if (! mMayPlayNetMusic) {
                String netName = Network.getActiveNetWorkName(getApplicationContext());
                if (!TextUtils.isEmpty(netName) && netName.toLowerCase().startsWith("mobile")) {
                    // 如果不是wifi条件下，就弹出是否需要在2G/3G/4G条件下，试听歌曲
                    showConfirmPlayNetMusicDialog();
                    return;
                }
			}
		}
		startPrepare(path);

		doPlay();
	}

	private void playFromPause() {
		Log.i("zxq", "play() mSeekTo = " + mSeekTo);
		mIsPause = false;
		if (!mIsPreparing) {
			mPlayer.start();
			mPlayer.seekTo(mSeekTo);
		}
		mHandler.sendEmptyMessage(1);
		ManagerFactory.getPlayerInstance().setPlayerState(
				IPlayerManager.PLAYER_STATE_PLAYING);

		doPlay();
	}

	private void doPlay() {
		sendPlayerState(ACTION_PLAY);
		showNotification(true);
	}


	private void playBelowVersion18() {
		Log.i("zxq", "play()");
		mAam.requestAudioFocus(mOfcl, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
		if (mLstMusic == null || mLstMusic.size() ==0) {
			ToastUtil.showShort(getApplicationContext(), R.string.mbx_play_list_is_empty);
			return;
		} else if (mMusicIndex >= mLstMusic.size() || mMusicIndex < 0) {
			mMusicIndex = 0;
		}
		if (mPlayer == null) {
			initPlayer();
		}
		// 不是从暂停状态进入播放状态
		if (!mIsPause) {
			mMapIcon.clear();
			mCurrentMusic = mLstMusic.get(mMusicIndex);
			if(mCurrentMusic == null){
				ToastUtil.showShort(getApplicationContext(), R.string.mbx_music_file_error);
				return;
			}
			commitMusicId();
			ManagerFactory.getPlayerInstance().setCurrentMusic(mCurrentMusic);
			mPlayer.reset();
			String path = mCurrentMusic.getMusicPath();//获取音乐在sd卡的路径地址
			String hq_path = mCurrentMusic.getHQMusicPath();//获取高清音乐在sd卡的路径地址,by jiagnwb
			//if(mCurrentMusic.isDownLoaded() && new File(hq_path).isFile()){ // 已下载
			if(new File(hq_path).isFile()){ // 已下载
				Log.i("MusicService.java -- jiangwb", "mHQMusicIndex=" + mMusicIndex + ",hq_path=" + hq_path);
				path = hq_path;// by jiangwb ,如果sd卡有高清音质，默认先播放高清音质的
				mCurrentMusic.setHQ(true);
				mIsNetMusic = false;
				mBufferPercent = -1;
				//}else  if (mCurrentMusic.isDownLoaded() && new File(path).isFile()) {           // 已下载
			}else  if (new File(path).isFile()) {           // 已下载
				Log.i("zxq", "mMusicIndex=" + mMusicIndex + ",path=" + path);
				mIsNetMusic = false;
				mBufferPercent = -1;
			} else {
				path = mCurrentMusic.getMusicUrl();
				if (TextUtils.isEmpty(path) || !URLUtil.isValidUrl(path)) {
					ToastUtil.showShort(getApplicationContext(), R.string.mbx_music_file_error);
					sendPlayerState(ACTION_PAUSE);
					return;
				}
				Log.i("zxq", "mMusicIndex=" + mMusicIndex + ",url=" + path);
				mSeekTo = 0;
				mIsNetMusic = true;
				mBufferPercent = 0;
			}
			Intent intent = MusicBoxUtils.getMusicServiceActionIntent();
			intent.putExtra(MUSIC_INFO, mCurrentMusic);
			sendBroadcast(intent);
			ConfigHelper.getInstance(getApplicationContext()).saveLongKey(MUSIC_ID,
					mCurrentMusic.getId());
			if (mIsNetMusic) {
				if (!Network.isNetworkAvaliable(getApplicationContext())) {
					ToastUtil.showShort(getApplicationContext(),
							R.string.mbx_no_net_for_play_net_music);
					sendPlayerState(ACTION_STOP);
					showNotification(false);
					return;
				} else if (!mMayPlayNetMusic) {
                    String netName = Network.getActiveNetWorkName(getApplicationContext());
                    if (!TextUtils.isEmpty(netName) && netName.toLowerCase().startsWith("mobile")) {
                        //如果不是wifi条件下，就弹出是否需要在2G/3G/4G条件下，试听歌曲
                        showConfirmPlayNetMusicDialog();
                        return;
                    }
                }
			}
			startPrepare(path);
		} else {
			Log.i("zxq", "play() mSeekTo = " + mSeekTo);
			if (mIsNetMusic && mDuration > 0) {
				int playPercent = mSeekTo * n100 / mDuration;
				// 无网络，且已播放到缓冲位置
				if (mBufferPercent > 1 && mBufferPercent < n100
						&& playPercent >= mBufferPercent - 1
						&& !Network.isNetworkAvaliable(getApplicationContext())) {
					ToastUtil.showShort(getApplicationContext(), R.string.mbx_no_net_for_play_net_music);
					return;
				}
			}
			mIsPause = false;
			if (!mIsPreparing) {
				mPlayer.start();
				mPlayer.seekTo(mSeekTo);
			}
			mHandler.sendEmptyMessage(1);
			ManagerFactory.getPlayerInstance().setPlayerState(IPlayerManager.PLAYER_STATE_PLAYING);
		}
		sendPlayerState(ACTION_PLAY);
		showNotification(true);
		return;
	}

	/***********************************************************************************/

	/**
	 * 提交当前播放音乐的ID
	 * Created 2014-11-4 下午10:43:26
	 * @author       zxq
	 */
	private void commitMusicId() {
		new Thread() {
			@Override
			public void run() {
				try {
					ApiManager.getInstance(getApplicationContext()).postPlayingID(mCurrentMusic);
				} catch (NdException e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	/**
	 * 启动准备
	 *
	 * @param musicPath
	 *            歌曲路径
	 * @author zxq
	 * @date 2014-8-16 下午7:51:57
	 */
	private void startPrepare(String musicPath) {
		if (mPrepareTask != null) {
			mPrepareTask.cancel();
		}
		mPrepareTask = new PrepareTask(musicPath);
		mPrepareTask.execute();
	}

	/**
	 * 准备歌曲线程
	 *
	 * @author zxq
	 * @date 2014-8-16 下午8:06:08
	 */
	private class PrepareTask extends NdThread {
		private MusicInfo mMusic;
		private String mPath;

		/**
		 * Creates a new instance of PrepareTask. <br>
		 * Created 2014年9月15日 下午11:14:38
		 *
		 * @param path
		 *            歌曲路径
		 */
		public PrepareTask(String path) {
			super();
			this.mMusic = mCurrentMusic;
			this.mPath = path;
			ManagerFactory.getPlayerInstance()
			.setPlayerState(IPlayerManager.PLAYER_STATE_PREPARING);
		}

		@Override
		protected void doSuccess(Object result) {
			mIsPreparing = false;
			if (!mMusic.equals(mCurrentMusic)) {
				return;
			}
			Intent intent =MusicBoxUtils.getMusicServiceActionIntent();
			mDuration = mPlayer.getDuration();
			intent.putExtra(MUSIC_DURATION, mDuration);
			if (!mIsNetMusic) {
				sendBuffered(-1);
			}
			intent.putExtra(MUSIC_INFO, mCurrentMusic);
			ConfigHelper.getInstance(getApplicationContext()).saveIntKey(MUSIC_DURATION, mDuration);
			sendBroadcast(intent);
			if (!mIsPause && mPlayer != null) {
				mPlayer.start();
				ManagerFactory.getPlayerInstance().setPlayerState(
						IPlayerManager.PLAYER_STATE_PLAYING);
				if (mSeekTo > 0) {
					mPlayer.seekTo(mSeekTo);
				}
				mHandler.sendEmptyMessage(1);
				showNotification(true);
			}
		}

		@Override
		protected void doFail(NdException result) {
			mIsPreparing = false;
			ManagerFactory.getPlayerInstance().setPlayerState(IPlayerManager.PLAYER_STATE_STOPPED);
		}

		@Override
		protected Object doInBackground() throws NdException {
			try {
				ManagerFactory.getPlaylistInstance(getApplicationContext()).addMusic2LastPlayed(
						mCurrentMusic);
				mIsPreparing = true;
				mPlayer.setDataSource(mPath);
				mPlayer.prepare();
				return null;
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			throw new NdException("");
		}
	}

	/**
	 * 显示通知栏 Created 2014-7-12 下午9:04:12
	 *
	 * @param isPlaying boolean
	 * @author zxq
	 */
	private void showNotification(final boolean isPlaying) {
		if (mLstMusic == null || mLstMusic.isEmpty()) {
			ToastUtil.showShort(getApplicationContext(), R.string.mbx_play_list_is_empty);
			return;
		}
        if (mCurrentMusic == null) {
            return;
        }
		if (mNm == null) {
			// 获取通知栏系统服务对象
			mNm = (NotificationManager) getApplicationContext().getSystemService(
					Context.NOTIFICATION_SERVICE);
		}
		Log.i("zxq", "showNotification歌曲名 = " + mCurrentMusic.getMusicName());
		final String imageUrl = mCurrentMusic.getImgUrl(GlobalSetting.MUSIC_ICON_SIZE);
		mNm.notify(0, new MusicNotification(this, isPlaying, mCurrentMusic, null));
		if (mMapIcon.containsKey(imageUrl)) {
			Bitmap bitmap = mMapIcon.get(imageUrl);
			if (mMapIcon.get(imageUrl) != null) {
				mNm.notify(0, new MusicNotification(this, isPlaying, mCurrentMusic, bitmap));
			}
			return;
		}
		mMapIcon.put(imageUrl, null);
		ImageLoaderUtil.loadImage(imageUrl, new SimpleImageLoadingListener() {
			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				super.onLoadingComplete(imageUri, view, loadedImage);
				mMapIcon.put(imageUrl, loadedImage);
				mNm.notify(0, new MusicNotification(getApplicationContext(), isPlaying,
						mCurrentMusic, loadedImage));
			}
		});
	}

	/**
	 * 暂停 Created 2014-7-8 下午10:58:34
	 *
	 * @author zxq
	 */
	private void pause() {
		if (mPlayer != null) {
			mSeekTo = mPlayer.getCurrentPosition();
			Log.i("zxq", "pause() mSeekTo = " + mSeekTo);
			savePosition(mSeekTo);
			if (mPlayer.isPlaying()) {
				mPlayer.pause();
			}
			mIsPause = true;
		}
		ManagerFactory.getPlayerInstance().setPlayerState(IPlayerManager.PLAYER_STATE_PAUSED);
		sendPlayerState(ACTION_PAUSE);
		showNotification(false);
		mHandler.removeMessages(1);
	}

	/**
	 * 上一首 Created 2014-7-8 下午10:58:42
	 *
	 * @author zxq
	 */
	private void prev() {
		Log.i("zxq", "prev()");
		stop(false);
		getNextIndex(false);
		play();
	}

	/**
	 * 下一首 Created 2014-7-8 下午10:58:51
	 *
	 * @author zxq
	 */
	private void next() {
		stop(false);
		getNextIndex(true);
		play();
	}

	/**
	 * 停止 Created 2014-7-8 下午10:59:03
	 * @param isShowState boolean
	 * @author zxq
	 */
	private void stop(boolean isShowState) {
		if (mPrepareTask != null) {
			mPrepareTask.cancel();
		}
		ManagerFactory.getPlayerInstance().setPlayerState(IPlayerManager.PLAYER_STATE_STOPPED);
		releaseMediaPlayer();
		mHandler.removeMessages(1);
		if (isShowState) {
			showNotification(false);
		}
		sendPlayerState(ACTION_STOP);
		savePosition(0);
	}

	@SuppressLint("NewApi")
	@Override
	public void onDestroy() {
		Log.i("zxq", "onDestroy()");
		// 停止准备线程
		if (mPrepareTask != null) {
			mPrepareTask.cancel();
		}
		savePosition(0);
		mHandler.removeMessages(1);
		releaseMediaPlayer();
		if (mNetStateReceiver != null) {
			unregisterReceiver(mNetStateReceiver);
		}
		if (mNm != null) {
			mNm.cancel(0);
		}
		if (mAam != null && mOfcl != null) {
			mAam.abandonAudioFocus(mOfcl);
		}
		ManagerFactory.getPlayerInstance().setCurrentMusic(null);
		ManagerFactory.getPlayerInstance().setPlayerState(IPlayerManager.PLAYER_STATE_STOPPED);
		ConfigHelper.getInstance(getApplicationContext()).saveBooleanKey(MUSIC_ISPLAYING, false);
		super.onDestroy();
	}

	/**
	 * 释放媒体播放器 Created 2014-10-21 下午8:14:10
	 *
	 * @author zxq
	 */
	private void releaseMediaPlayer() {
		if (mPrepareTask != null) {
			mPrepareTask.cancel();
		}
		if (mPlayer != null) {
			mPlayer.release();
			mPlayer = null;
		}
		mIsPreparing = false;
		mIsPause = false;
		mSeekTo = 0;
	}

	/**
	 * 消息处理器 Created 2014年9月15日 下午11:14:46
	 *
	 * @version MusicService
	 * @author zxq
	 * @see
	 */
	@SuppressLint("HandlerLeak")
	private class MusicHandler extends Handler {
		private Intent mIntent = MusicBoxUtils.getMusicServiceActionIntent();

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (1 == msg.what) {
				int position = mPlayer.getCurrentPosition();
				if (position >= 0 && position <= mDuration) {
					savePosition(position);
					mIntent.putExtra(MUSIC_POSITION, position);
					sendBroadcast(mIntent);
					sendEmptyMessageDelayed(1, n200);
					if (mIsNetMusic && mDuration > 0) {
						int playPercent = position * n100 / mDuration;
						// 无网络，且已播放到缓冲位置
						if (mBufferPercent > 1 && mBufferPercent < n100
								&& playPercent >= mBufferPercent - 1
								&& !Network.isNetworkAvaliable(getApplicationContext())) {
							mHandler.removeMessages(1);
							pause();
						}
					}
				}
			}
		}
	}

	/**
	 * 缓冲变化时 Created 2014-7-8 下午9:24:52
	 *
	 * @param mp
	 *            播放器
	 * @param percent
	 *            缓冲进度，百分比
	 * @author zxq
	 */
	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		mBufferPercent = percent;
		int buffered = percent * mDuration / n100;
		if (buffered > 0 && buffered <= mDuration) {
			sendBuffered(buffered);
		}
	}

	/**
	 * 发送缓冲进度广播 Created 2014-7-27 上午12:06:42
	 *
	 * @param buffer
	 *            缓冲进度
	 * @author zxq
	 */
	private void sendBuffered(int buffer) {
		Intent intent = MusicBoxUtils.getMusicServiceActionIntent();
		intent.putExtra(MUSIC_BUFFERED, buffer);
		sendBroadcast(intent);
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		Log.i("zxq", "onError");
		releaseMediaPlayer();
		initPlayer();
		sendPlayerState(ACTION_STOP);
        updateCurrentMusicAndIndex();
        showNotification(false);
		if (mIsNetMusic && !Network.isNetworkAvaliable(getApplicationContext())) {
			ToastUtil.showShort(getApplicationContext(), R.string.mbx_no_net_for_play_net_music);
		}
		return true;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		LogUtils.v("MusicService.java -- jiangwb", "onCompletion() -- 播放完成，切换到下一曲");
		// 网络歌曲，播放到缓冲位置时，会调用 onCompletion方法
		//        int position = mPlayer.getCurrentPosition();
		//        // 播放进度达到99%时也认为已播放完成
		//        if (mIsNetMusic && position < mDuration && (mDuration - position) * n100 >= mDuration) {
		//            pause();
		//            return;
		//        }
		mSeekTo = 0;
		if (LOOP_TYPE_LOOPING != mLoopType) {
			getNextIndex(true);
		}
		play();
	}

	/**
	 * 获取下一首的序号 Created 2014-7-10 上午12:31:48
	 *
	 * @param isNext
	 *            是否是下一首
	 * @author zxq
	 */
	private void getNextIndex(boolean isNext) {
		if (mLstMusic == null || mLstMusic.isEmpty()) {
			LogUtils.d("MusicService.java -- jiangwb", "getNextIndex() -- isNext:" + isNext + " reason:播放列表为空");
			ToastUtil.showShort(getApplicationContext(), R.string.mbx_play_list_is_empty);
			return;
		}
		switch (mLoopType) {
		case LOOP_TYPE_LOOPING:
			// 顺序播放
		case LOOP_TYPE_ORDER:
			getNext(isNext);
			break;
			// 随机播放
		case LOOP_TYPE_RADOM:
			// 只有一首时，会进入死循环
			if (mLstMusic.size() > 1) {
				Random random = new Random(System.currentTimeMillis());
				int index = random.nextInt(mLstMusic.size());
				if (mMusicIndex == index) {
					getNext(isNext);
				} else {
					mMusicIndex = index;
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 获取下一个序号 <br>
	 * Created 2014-11-4 下午10:00:26
	 *
	 * @param isNext
	 *            是否是下一首
	 * @author zxq
	 */
	private void getNext(boolean isNext) {
		if (isNext) {
			// 下一首, 防止mMusicIndex < 0的情况出现
			mMusicIndex += (mLstMusic.size() + 1);
		} else {
			// 上一首, 防止mMusicIndex < 0的情况出现
			mMusicIndex += (mLstMusic.size() - 1);
		}
		mMusicIndex %= mLstMusic.size();
	}

	/**
	 *
	 * 网络状态改变监听广播 Created 2014年9月15日 下午11:15:05
	 *
	 * @version MusicService
	 * @author zxq
	 * @see
	 */
	private class NetStateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 网络状态改变
			if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
				// 本地歌曲，无影响
				if (!mIsNetMusic) {
					return;
				}
				String netName = Network.getActiveNetWorkName(context);
				if (!TextUtils.isEmpty(netName) && netName.toLowerCase().startsWith("mobile")) {
					if (!mIsPause) {
                        pause();
                        showConfirmPlayNetMusicDialog();
                    }
				}
			}
		}
	}

	/**
	 * 显示是否播放网络音乐对话框 Created 2014年9月15日 下午11:15:10
	 *
	 * @author zxq
	 */
	private void showConfirmPlayNetMusicDialog() {
		if (mConfirmPlayNetMusicDialog != null && mConfirmPlayNetMusicDialog.isShowing()) {
			return;
		}
		Builder builder = new AlertDialog.Builder(getApplicationContext());
		builder.setTitle(R.string.mbx_hint).setMessage(R.string.mbx_is_play_net_music)
		.setIcon(android.R.drawable.ic_dialog_alert)
		.setPositiveButton(R.string.mbx_confirm, new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				mMayPlayNetMusic = true;
				play();
			}
		}).setNegativeButton(R.string.mbx_cancel, new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				mMayPlayNetMusic = false;
				stop(true);
			}
		});
		mConfirmPlayNetMusicDialog = builder.create();
		// 全局对话框
		mConfirmPlayNetMusicDialog.getWindow()
		.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		mConfirmPlayNetMusicDialog.show();
	}

	/**
	 * 保存播放进度 Created 2014-7-17 下午11:23:53
	 *
	 * @param position
	 *            播放进度
	 * @author zxq
	 */
	private void savePosition(int position) {
		mSeekTo = position;
		ConfigHelper.getInstance(getApplicationContext()).saveIntKey(MUSIC_SEEKTO, position);
	}

	/**
	 * 保存播放状态 Created 2014-7-26 下午3:45:11
	 *
	 * @param action
	 *            播放动作
	 * @author zxq
	 */
	private void sendPlayerState(int action) {
		ConfigHelper.getInstance(getApplicationContext()).saveBooleanKey(MUSIC_ISPLAYING,
				action == ACTION_PLAY);
		Intent intent = new Intent(MusicBoxUtils.getMusicServiceAction());
		intent.putExtra(PLAYER_ACTION, action);
		sendBroadcast(intent);
	}
}
